package com.bw.common.network.inteceptor;

import com.bw.common.utils.SignUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Iterator;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

public class SignInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request oldRequest = chain.request();
        Request.Builder builder = new Request.Builder();
        builder.url(oldRequest.url());
        builder.headers(oldRequest.headers());
        RequestBody oldBody = oldRequest.body();
        Buffer buffer = new Buffer();
        oldBody.writeTo(buffer);
        String jsonStr = buffer.readUtf8();
        buffer.close();
        RequestBody body=null;
        //每个接口请求中请求参数不相同->获取全部请求参数值{"key":"value"}
        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
            StringBuffer stringBuffer = new StringBuffer();
            Iterator<String>it = jsonObject.keys();//json中全部得key生成一个迭代器
            while (it.hasNext()){
                stringBuffer.append(jsonObject.getString(it.next()));
            }
            //sign加密生成
            String sign = SignUtils.createSign(stringBuffer.toString());
            jsonObject.put("sign",sign);
            body = RequestBody.create(MediaType.parse("application/json"),jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }finally {
            if (body == null)
                body = oldBody;
        }
        builder.post(body);
        return chain.proceed(builder.build());
    }
}
